#pragma once
#include "../logger.hpp"
#include "friend_apply.hxx"
#include "friend_apply-odb.hxx"
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <odb/database.hxx>
#include <odb/mysql/database.hxx>
#include <sstream>
#include <string>
#include <vector>

namespace shared {

namespace dal {

class FriendApplyDao;
using FriendApplyDaoPtr = std::shared_ptr<FriendApplyDao>;

class FriendApplyDao
{
    using query = odb::query<entity::FriendApply>;
    using result = odb::result<entity::FriendApply>;
public:
    FriendApplyDao(const std::shared_ptr<odb::mysql::database>& db) : db_(db) {}

    // 新增一条好友申请记录
    bool insert(entity::FriendApply& friendApply)
    {
        try {
            odb::transaction trans(db_->begin());
            db_->persist(friendApply);
            trans.commit();
        } catch (const std::exception& e) {
            LOG_ERROR("向好友申请表新增记录({}-{})失败: {}", friendApply.requesterId(), friendApply.receiverId(), e.what());
            return false;
        }
        return true;
    }
    // 移除一条好友申请记录
    bool remove(const std::string& reqId, const std::string& recvId)
    {
        try {
            odb::transaction trans(db_->begin());
            db_->erase_query<entity::FriendApply>(
                query::requesterId == reqId &&
                query::receiverId == recvId
            );
            trans.commit();
        } catch (const std::exception& e) {
            LOG_ERROR("从用户申请表删除申请记录({}-{})失败: {}", reqId, recvId, e.what());
            return false;
        }
        return true;
    }
    // 判断指定该用户是否已经向对方发起过好友申请
    bool exists(const std::string& reqId, const std::string& recvId)
    {
        bool ret;
        try {
            odb::transaction trans(db_->begin());
            ret = db_->query<entity::FriendApply>(
                query::requesterId == reqId && query::receiverId == recvId
            ).size();
            trans.commit();
        } catch (const std::exception& e) {
            LOG_ERROR("向用户关系表删除关系({}-{})失败: {}", reqId, recvId, e.what());
            return false;
        }
        return ret;
    }
    // 获取指定用户的好友ID列表
    std::vector<std::string> selectFriendApply(const std::string& userId)
    {
        std::vector<std::string> res;
            try {
                odb::transaction trans(db_->begin());
                result ret(db_->query<entity::FriendApply>(query::receiverId == userId));   // 被申请方(申请的接收方)是自己
                for (auto it = ret.begin(); it != ret.end(); ++it) {
                    res.push_back(it->requesterId());
                }
                trans.commit(); 
            } catch (const std::exception& e) {
                LOG_ERROR("获取用户({})的好友申请列表失败: {}", userId, e.what());
        }
        return res;
    }
private:
    std::shared_ptr<odb::mysql::database> db_;
};


}}